<?php
include './config/config.php';

if ($_POST) {
  $salt = build_ranstr();
  $password = md5($_POST['password'] . $salt);

  // todo 检查名字是否存在
  if ($_POST['action'] == 'check') {
    $val = $_POST['val'];

    $sql = "SELECT * FROM `pre_admin` WHERE `username` = '$val'";

    $data = query($sql);

    if ($data) {
      error("用户名已存在");
    } else {
      success("用户名可以使用");
    }
  }

  // ? 接收提交参数
  $formData = array(
    'username' => $_POST['username'],
    'password' => $password,
    'salt' => $salt
  );



  //  todo 检测文件是否上传
  if ($_FILES['avatar'] && $_FILES['avatar']['size'] > 0) {
    $file = upload("avatar");
    if ($file['code'] == 0) {
      ShowMsg($file['msg']);
      exit;
    } else {
      // ? 数据追加avatar
      $formData['avatar'] = $file['url'];
    }
  } else {
    ShowMsg("请上传一张图片");
    exit;
  }

  $res = insertInfo('admin', $formData);

  if ($res) {
    ShowMsg($res['msg'], "adminList.php");
  } else {
    ShowMsg('插入失败', "adminList.php");
  }
}
?>

<!DOCTYPE html>
<html lang="en">

<head>
  <?php include_once('common/meta.php'); ?>
</head>

<body>

  <?php include_once('common/header.php'); ?>

  <?php include_once('common/menu.php'); ?>

  <div class="content">
    <div class="header">
      <h1 class="page-title">添加管理员</h1>
    </div>
    <ul class="breadcrumb">
      <li><a href="adminList.php">AdminList</a> <span class="divider">/</span></li>
      <li class="active">Index</li>
    </ul>

    <div class="container-fluid">
      <div class="row-fluid">

        <div class="btn-toolbar">
          <button class="btn btn-primary" onClick="location='adminList.php'"><i class="icon-list"></i> 管理员列表</button>
          <div class="btn-group">
          </div>
        </div>

        <div class="well">
          <div id="myTabContent" class="tab-content">
            <div class="tab-pane active in" id="home">
              <form id="add_form" method="POST" action="adminAdd.php" enctype="multipart/form-data">
                <label>用户名</label>
                <input type="text" name="username" required>
                <span id="username"></span>

                <label>密码</label>
                <input type="password" name="password" required>

                <label for="avatar">头像</label>
                <input type="file" name="avatar" id="avatar" hidden>
                <label class="avatar" for="avatar">
                  <img src="assets/images/upload.png" alt="" id="img" width="120">
                </label>

                <label for=""></label>
                <input class="btn btn-primary" type="submit" value="提交" />
              </form>
            </div>
          </div>
        </div>

        <?php include_once('common/footer.php'); ?>

      </div>
    </div>
  </div>

  <script src="./assets/lib/jquery-1.8.1.min.js"></script>
  <script>
    // 图片预览函数
    function GetObjectURL(file) {
      // createObjectURL  给一个文件对象 可以提取出一个url本地地址出来
      var url = null;

      //判断是否为IE浏览器还是google还是其他浏览器
      if (window.createObjectURL != undefined) {
        url = window.createObjectURL(file)
      } else if (window.URL != undefined) {
        url = window.URL.createObjectURL(file)
      } else if (window.webkitURL != undefined) {
        url = window.webkitURL.createObjectURL(file)
      }

      return url
    }

    $("#avatar").change(function() {
      let file = $(this)[0].files[0] ? $(this)[0].files[0] : {};
      // console.log(file[0].files[0]);

      // return false;
      let url = GetObjectURL(file);
      $("#img").attr('src', url);
    });

    // todo 检测用户名
    $('input[name="username"]').change(function(e) {
      let val = $(this).val();
      $.ajax({
        type: "post",
        url: "adminAdd.php",
        data: {
          val,
          action: 'check'
        },
        dataType: "json",
        success: function(res) {
          if (res.code === 1) {
            $("#username").html(res.msg).css({
              "color": "green"
            });
          } else if (res.code === 0) {
            $("#username").html(res.msg).css({
              "color": "red"
            });
          }
        },
        error: function(err) {
          console.log(err);
        }
      });
    })
  </script>
</body>

</html>
<?php include_once('common/script.php'); ?>